package middleware

import (
	"github.com/gin-gonic/gin"
	"gspeed/app/dist"
	"gspeed/app/utils/response"
	"gspeed/bootstrap/global"
	"net/http"
	"strconv"
)

func Permission() gin.HandlerFunc {
	return func(c *gin.Context) {
		userId, _ := c.Get("UserId")
		id := strconv.Itoa(int(userId.(float64)))

		path := c.Request.URL.Path
		method := c.Request.Method

		// 加载策略规则（不需要每个请求都LoadPolicy）
		/*err := global.Auth.LoadPolicy()
		if err != nil {
			panic(err)
		}*/
		// 验证策略规则
		ok, err := global.Auth.Enforce(id, path, method)
		if err != nil {
			// 处理err
			response.Err(c, response.WithHttpStatus(http.StatusNotFound), response.WithCode(dist.PermissionError))
			return
		}
		if ok == false {
			// 拒绝请求
			response.Err(c, response.WithHttpStatus(http.StatusForbidden), response.WithCode(dist.PermissionForbidden))
			return
		}
		// 权限通过
		c.Next()
	}
}
